package com.zhb.cloud.service.impl;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.zhb.cloud.core.distribute.lock.DistributedLock;
import com.zhb.cloud.core.distribute.lock.DistributedLockPath;
import com.zhb.cloud.core.distribute.lock.DistributedLockUtils;
import com.zhb.cloud.core.distribute.lock.LockFactory;
import com.zhb.cloud.core.util.JsonReturn;
import com.zhb.cloud.core.util.PrizeUtils;
import com.zhb.cloud.mapper.PrizeMapper;
import com.zhb.cloud.mapper.UserAwardMapper;
import com.zhb.cloud.mapper.UserMapper;
import com.zhb.cloud.model.Prize;
import com.zhb.cloud.model.UserAward;
import com.zhb.cloud.service.UserService;

@Service
public class UserServiceImpl implements UserService {
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private PrizeMapper prizeMapper;
	@Autowired
	private UserAwardMapper awardMapper;
	@Autowired
	private LockFactory lockFactory;

	/**
	 * 抽奖的具体实现
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public JsonReturn award(Integer userId) {
		JsonReturn jsonReturn = new JsonReturn();
		// 1.计算中奖奖品
		List<Prize> prizes = prizeMapper.findPrizeList();
		int index = PrizeUtils.getPrizeIndex(prizes);// 中奖的序号
		// 1.1中奖奖品
		Prize awardPrize = null;
		for (Prize prize : prizes) {
			if (prize.getPrizeOrder() == index) {
				awardPrize = prize;
				break;
			}
		}
		DistributedLock lock = lockFactory.obtainLock(DistributedLockPath.AWARD_PATH);
		try {
			Thread.sleep(6000);
			if (DistributedLockUtils.tryLockQuietly(lock, 3000, TimeUnit.MILLISECONDS)) {
				// 2.减库存
				// 2.1查询奖品的剩余数量
				Prize prize = prizeMapper.selectByPrimaryKey(awardPrize.getId());
				if (prize.getPrizeAmount() < 1) {
					jsonReturn.setCode(100);
					jsonReturn.setMessage("库存不足");
				} else {
					prizeMapper.reducePrizeNum(prize.getId());
					// 3.插入抽奖纪录
					UserAward userAward = new UserAward();
					userAward.setPrizeId(prize.getId());
					userAward.setUserId(userId);
					userAward.setCreateTime(new Date());
					awardMapper.insertSelective(userAward);
					// 4 .减少用户的抽奖次数
					userMapper.reduceAwardCount(userId);
					// 抽奖成功返回奖品
					jsonReturn.setCode(200);
					jsonReturn.setData(prize);
					jsonReturn.setMessage("抽奖成功");
				}
			}
		} catch (Exception exception) {
			jsonReturn.setCode(100);
			jsonReturn.setMessage("抽奖失败");
		} finally {
			DistributedLockUtils.unlockQuietly(lock); // 释放锁
		}
		return jsonReturn;
	}
}
